using Microsoft.AspNetCore.Mvc;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Repositories;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 用户基本科室权限查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UserPermissionController : ControllerBase
    {
        private readonly IUserPermissionRepository _userPermissionRepository;

        public UserPermissionController(IUserPermissionRepository userPermissionRepository)
        {
            _userPermissionRepository = userPermissionRepository;
        }

        /// <summary>
        /// 根据用户名查询用户基本科室权限
        /// 使用Oracle HIS数据库
        /// </summary>
        /// <param name="request">包含用户名的请求</param>
        /// <returns>用户权限查询结果</returns>
        [HttpPost("GetUserPermissions")]
        public async Task<ActionResult<UserPermissionResult>> GetUserPermissions([FromBody] UserPermissionRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new UserPermissionResult
                    {
                        Success = false,
                        Message = "请求参数无效",
                        Data = new List<UserPermissionResponse>()
                    });
                }

                var permissions = await _userPermissionRepository.GetUserPermissionsByUsernameAsync(request.Username);

                if (permissions.Count == 0)
                {
                    return Ok(new UserPermissionResult
                    {
                        Success = false,
                        Message = $"用户 '{request.Username}' 未找到相关科室权限数据",
                        Data = new List<UserPermissionResponse>()
                    });
                }

                return Ok(new UserPermissionResult
                {
                    Success = true,
                    Message = $"查询成功，找到 {permissions.Count} 条权限记录",
                    Data = permissions
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new UserPermissionResult
                {
                    Success = false,
                    Message = $"查询用户基本科室权限失败: {ex.Message}",
                    Data = new List<UserPermissionResponse>()
                });
            }
        }
    }
}